package com.james.codeauto.web;

import com.james.codeauto.common.FieldHelper;
import com.james.codeauto.common.StringUtils;
import com.james.codeauto.entity.FieldApiInfo;
import com.james.codeauto.tools.json.JSONArray;
import com.james.codeauto.tools.json.JSONException;
import com.james.codeauto.tools.json.JSONObject;
import com.james.codeauto.util.*;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class FetchWebData {

    public static void main(String argsp[]) throws Exception {
     //   List<Map<String, Object>> iteL = new FetchWebData().paseHtmlData("3176");
        //   List<Map<String, Object>> iteL = DocUtil.parseHtmlData();
     //      List<Map<String, Object>> iteL = ParkingLotInnerDocUtil.parseHtmlData();
        //List<Map<String, Object>> iteL = ParkingLotDocUtil.parseHtmlData();
     //   List<Map<String, Object>> iteL = ParkingLotRobotDocUtil.parseHtmlData();
     //   List<Map<String, Object>> iteL = ParkingLotYuShiDocUtil.parseHtmlData();
     //   List<Map<String, Object>> iteL = ParkingLotJieShunDocUtil.parseHtmlData();
        List<Map<String, Object>> iteL = LiveDocUtil.parseInfoList();
        for (int i = 0; i < iteL.size(); i++) {
            Map<String, Object> jsonObject = iteL.get(i);
            String info = (String) jsonObject.get("jsonCommentStr");
            Map<String, FieldApiInfo> item = FieldHelper.getFieldApiInfo(info, "");
            String dtoName = TransApi.getTransResultDtoName((String) jsonObject.get("title"));
            jsonObject.put("dtoName", dtoName);
            jsonObject.put("fieldApiInfo", item);
            GenUtils.generatorCode(jsonObject);
        }
        GenUtils.generatorMethodCode(iteL);
    }

    private static int errCount = 0;

    public List<Map<String, Object>> paseHtmlData(String page_id) {
        List<Map<String, Object>> listData = new ArrayList<>();
        JSONArray pages = null;
        if (StringUtils.isNotBlank(page_id)) {
            pages = new JSONArray().put(new JSONObject().put("page_id", page_id));
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("item_id", 35);
            jsonObject.put("default_page_id", 167);
            JSONObject html = HttpClient.doPostForJson("http://doc.wuuxiang.com/showdoc/server/index.php?s=/api/item/info", jsonObject, true);
            JSONArray catalogs = html.optJSONObject("data").optJSONObject("menu").optJSONArray("catalogs");
            pages = new JSONArray().put(catalogs.getJSONObject(0).getJSONArray("catalogs").getJSONObject(1));
            pages = getAllPages(pages, new JSONArray());

        }

        for (int i = 0; i < pages.length(); i++) {
            JSONObject page = pages.getJSONObject(i);

            JSONObject result = HttpClient.doPostForJson("http://doc.wuuxiang.com/showdoc/server/index.php?s=/api/page/info", page, true);
            JSONObject data = result.optJSONObject("data");
            if (data == null) {
                continue;
            }
            String markDownContent = data.getString("page_content");
            if (!StringUtils.isNotBlank(page.optString("page_title"))) {
                page.put("page_title", result.optJSONObject("data").getString("page_title"));
            }
            checkSaveMarkdownToFile(page, markDownContent);
            List<Extension> extensions = Arrays.asList(TablesExtension.create());
            Parser parser = Parser.builder().extensions(extensions).build();

            Node document = parser.parse(markDownContent);
            HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
            String htmlText = renderer.render(document);  // "<p>This is <em>Sparta</em></p>\n"

            Document doc = Jsoup.parse(htmlText);
            Elements pElement = doc.getElementsByTag("p");
            Element element = pElement.first();
            if (!element.text().contains("简要描述")) {
                continue;
            }
            Map<String, Object> parseMap = new HashMap<>();
            Elements liElement = doc.getElementsByTag("li");
            for (int j = 0; j < liElement.size(); j++) {
                String content = liElement.get(j).text();
                if (j == 0) {
                    //简要描述
                    parseMap.put("desc", content);
                } else if (j == 1) {
                    if (content.contains("api")) {
                        //请求URL
                        parseMap.put("url", content);
                    }

                } else if (j == 2) {
                    if (content.contains("api")) {
                        //请求URL
                        parseMap.put("url", content);
                    } else {
                        //请求方式
                        parseMap.put("method", content);
                    }

                } else if (j == 3) {
                    if (content.toUpperCase().startsWith("POST") || content.toUpperCase().startsWith("GET")) {
                        //请求方式
                        parseMap.put("method", content);
                    }

                }
            }

            Elements codeElement = doc.getElementsByTag("pre");
            String jsonParam = codeElement.first().text();
            jsonParam = jsonParam.replaceAll("&quot;", "\"").replaceAll("，", ",");
            //error 1
            String pageTitle = page.getString("page_title");
            //跳过解析有问题接口
            if ("签名方法".equals(pageTitle)) {
                continue;
            } else if ("支付宝刷脸查询会员卡接口".equals(pageTitle)) {
                continue;
            } else if ("查询交易明细列表".equals(pageTitle)) {
                continue;
            } else if ("会员卡消费".equals(pageTitle)) {
                continue;
            } else if ("会员卡确认充值".equals(pageTitle)) {
                continue;
            } else if ("会员卡挂失/取消挂失".equals(pageTitle)) {
                continue;
            }

            parseMap.put("title", pageTitle);
            if (pageTitle.equals("会员卡智能消费")) {
                jsonParam = jsonParam.replace("\"companyId\": \"1000001056,", "\"companyId\": 1000001056,");
            } else if (pageTitle.equals("购买券订单列表（未发生退款）") || pageTitle.equals("购买券订单列表（发生退款）")) {
                jsonParam = jsonParam.replace("\"startDate\":\"2020-10-21 11:00:00\"", "\"startDate\":\"2020-10-21 11:00:00\",");

            }

            System.out.println(jsonParam);

            JSONObject param = new JSONObject(jsonParam);
            param.remove("companyId");
            parseMap.put("paramJson", param);
            String jsonResponse = codeElement.last().text();
            jsonResponse = jsonResponse.replaceAll("&quot;", "\"").replaceAll("，", ",");
            if (pageTitle.equals("会员卡智能消费")) {
                jsonResponse = jsonResponse.replace("\"companyId\": \"1000001056,", "\"companyId\": 1000001056,");
            } else if (pageTitle.equals("购买券订单列表（未发生退款）") || pageTitle.equals("购买券订单列表（发生退款）")) {
                jsonResponse = jsonResponse.replace("\"startDate\":\"2020-10-21 11:00:00\"", "\"startDate\":\"2020-10-21 11:00:00\",");

            } else if (pageTitle.equals("获取活动列表（基础信息）")) {
                jsonResponse = jsonResponse.replace("\"resultCode\": \"1200\",", "");
            } else if (pageTitle.equals("获取活动配置的券列表")) {
                jsonResponse = jsonResponse.replace("\"resultCode\": \"1200\",", "");
            } else if (pageTitle.equals("根据订单号查询券信息")) {
                jsonResponse = jsonResponse.replace("\"content\": \"{", "\"content\": {");
                jsonResponse = jsonResponse.replace("}\",", "},");
            } else if (pageTitle.equals("付费升级明细")) {
                jsonResponse = jsonResponse + "}";
            }
            System.out.println("\n" + pageTitle + "\n" + parseMap.get("url"));
            System.out.println(jsonResponse);
            if (jsonResponse.startsWith("[")) {
                parseMap.put("responseJson", new JSONArray(jsonResponse));
            } else {
                JSONObject response = new JSONObject(jsonResponse);
                if (response.optJSONObject("rpData") != null) {
                    parseMap.put("responseJson", response.optJSONObject("rpData"));
                } else if (response.optJSONArray("rpData") != null) {
                    parseMap.put("responseJson", response.optJSONArray("rpData"));
                }else{
                    parseMap.put("responseJson",response);
                }

            }

            Object jsonCommentObj = parseMap.get("responseJson");
            JSONObject jsonCommentParseTag = new JSONObject();
            if (jsonCommentObj instanceof JSONArray) {
                jsonCommentParseTag = ((JSONArray) jsonCommentObj).getJSONObject(0);
            } else {
                jsonCommentParseTag = (JSONObject) jsonCommentObj;
            }
            Elements tbodyElement = doc.getElementsByTag("tbody");
            Elements table1Element = tbodyElement.first().getElementsByTag("tr");
            JSONArray paramInfo = new JSONArray();
            for (int j = 0; j < table1Element.size(); j++) {
                Elements table1TdElement = table1Element.get(j).getElementsByTag("td");
                JSONObject jsonObjectParam = new JSONObject();
                for (int k = 0; k < table1TdElement.size(); k++) {
                    String paramStr = table1TdElement.get(k).text();

                    if (k == 0) {
                        //参数名
                        jsonObjectParam.put("name", paramStr);
                    } else if (k == 1) {
                        //必选
                        jsonObjectParam.put("require", paramStr);
                    } else if (k == 2) {
                        //类型
                        jsonObjectParam.put("type", paramStr);
                    } else if (k == 3) {
                        //说明
                        jsonObjectParam.put("desc", paramStr);
                    }
                    System.out.println(paramStr);
                }
                if ("companyId".equals(jsonObjectParam.optString("name"))) {
                    continue;
                }
                paramInfo.put(jsonObjectParam);
            }
            parseMap.put("paramList", paramInfo);
            Elements table2Element = tbodyElement.last().getElementsByTag("tr");
            JSONArray responseParamInfo = new JSONArray();

            for (int j = 0; j < table2Element.size(); j++) {
                Elements table2TdElement = table2Element.get(j).getElementsByTag("td");

                JSONObject jsonObjectParam = new JSONObject();
                int len = table2TdElement.size();
                if (len == 3) {
                    for (int k = 0; k < len; k++) {
                        String responseParamStr = table2TdElement.get(k).text();
                        System.out.println(responseParamStr);
                        jsonObjectParam.put("require", "是");
                        if (k == 0) {
                            //参数名
                            jsonObjectParam.put("name", responseParamStr);
                        } else if (k == 1) {
                            //类型
                            jsonObjectParam.put("type", responseParamStr);
                        } else if (k == 2) {
                            //说明
                            jsonObjectParam.put("desc", responseParamStr);
                        }
                        System.out.println(responseParamStr);
                    }
                } else {
                    for (int k = 0; k < len; k++) {
                        String responseParamStr = table2TdElement.get(k).text();
                        System.out.println(responseParamStr);
                        if (k == 0) {
                            //参数名
                            jsonObjectParam.put("name", responseParamStr);
                        } else if (k == 1) {
                            //必选
                            jsonObjectParam.put("require", responseParamStr);
                        } else if (k == 2) {
                            //类型
                            jsonObjectParam.put("type", responseParamStr);
                        } else if (k == 3) {
                            //说明
                            jsonObjectParam.put("desc", responseParamStr);
                        }
                        System.out.println(responseParamStr);
                    }
                }

                responseParamInfo.put(jsonObjectParam);

            }
            parseMap.put("responseParamList", responseParamInfo);
            listData.add(parseMap);
            //匹配字段 jsonCommentParseTag 多级迭代 ,
//            put(FIELD_NAME, 0);
//            put(FIELD_NAME_COMMENT, 1);
//            put(TYPE, 2);
//            put(REQUIRED, 3);
//            put(DEFAULT_VALUE, 4);
//            put(FIELD_DESC, 5);

            String reqJsonCommentStr = "";
            for (int j = 0; j < paramInfo.length(); j++) {
                JSONObject reqParamObject = paramInfo.getJSONObject(j);
                String desc = reqParamObject.optString("desc");
                if (!StringUtils.isNotBlank(desc)) {
                    desc = reqParamObject.getString("name");
                }
                reqJsonCommentStr += reqParamObject.getString("name") + "\t";
                reqJsonCommentStr += desc + "\t";
                reqJsonCommentStr += reqParamObject.optString("type") + "\t";
                reqJsonCommentStr += reqParamObject.optString("require") + "\t";
                reqJsonCommentStr += "" + "\t";
                reqJsonCommentStr += desc + "\n";

            }
            parseMap.put("reqJsonCommentStr", reqJsonCommentStr);

            String jsonCommentStr = "";
            for (int j = 0; j < responseParamInfo.length(); j++) {
                JSONObject responseParamObject = responseParamInfo.getJSONObject(j);
                String desc = responseParamObject.optString("desc");
                if (!StringUtils.isNotBlank(desc)) {
                    desc = responseParamObject.getString("name");
                }
                jsonCommentStr += responseParamObject.getString("name") + "\t";
                jsonCommentStr += desc + "\t";
                jsonCommentStr += responseParamObject.optString("type") + "\t";
                jsonCommentStr += responseParamObject.optString("require") + "\t";
                jsonCommentStr += "" + "\t";
                jsonCommentStr += desc + "\n";

            }
            parseMap.put("jsonCommentStr", jsonCommentStr);
            System.out.println(parseMap.toString());
        }

        //Document doc = Jsoup.parse(html);
        return listData;
    }

    public int testIsArrayORObject(String sJSON) {
        /*
         * return 0:既不是array也不是object
         * return 1：是object
         * return 2 ：是Array
         */
        if (sJSON.startsWith("{")) {
            JSONObject object = new JSONObject(sJSON);
            return 1;
        } else if (sJSON.startsWith("[")) {
            JSONArray object = new JSONArray(sJSON);
            return 2;
        } else {
            System.out.println("非法的JSON字符串");
            return 0;
        }

    }

    public String getKeys(JSONObject test) throws JSONException {

        String result = null;

        Iterator keys = test.keys();
        while (keys.hasNext()) {

            try {

                String key = keys.next().toString();
                String value = test.optString(key);

                int i = testIsArrayORObject(value);

                if (result == null || result.equals("")) {
                    if (i == 0) {

                        result = key + ",";
                        System.out.println("i=0 | key=" + key + "| result=" + result);


                    } else if (i == 1) {

                        result = key + ",";
                        System.out.println("i=1 | key=" + key + "| result=" + result);
                        result = getKeys(new JSONObject(value)) + ",";
                    } else if (i == 2) {

                        result = key + ",";
                        System.out.println("i=2 | key=" + key + "| result=" + result);
                        JSONArray arrays = new JSONArray(value);
                        for (int k = 0; k < arrays.length(); k++) {
                            JSONObject array = new JSONObject(arrays.get(k));
                            result = getKeys(array) + ",";
                        }
                    }

                } else {
                    if (i == 0) {

                        result = result + key + ",";
                        System.out.println("i=0 | key=" + key + "| result=" + result);


                    } else if (i == 1) {

                        result = result + key + ",";
                        System.out.println("i=1 | key=" + key + "| result=" + result);
                        result = result + getKeys(new JSONObject(value));
                    } else if (i == 2) {
                        result = result + key + ",";
                        System.out.println("i=2 | key=" + key + "| result=" + result);
                        JSONArray arrays = new JSONArray(value);
                        for (int k = 0; k < arrays.length(); k++) {
                            JSONObject array = new JSONObject(arrays.get(k));
                            result = result + getKeys(array) + ",";
                        }
                    }
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        return result;
    }


    boolean saveMarkDownFile = false;

    private void checkSaveMarkdownToFile(JSONObject page, String markDownContent) {
        if (saveMarkDownFile) {
            String title = page.getString("page_title");
            String fileName = title + ".md";
            if (title.startsWith("根据手机号给会员打标")) {
                fileName = "根据手机号给会员打标签-删除标签.md";
            } else if (title.startsWith("会员卡挂失")) {
                fileName = "会员卡挂失-取消挂失.md";
            }

            // 从JDK1.7开始提供的方法
            // 使用Files.write创建一个文件并写入
            try {
                Files.write(Paths.get(fileName), markDownContent.getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private JSONArray getAllPages(JSONArray catalogs, JSONArray allPages) {
        for (int i = 0; i < catalogs.length(); i++) {
            JSONObject jsonObject = catalogs.getJSONObject(i);
            if (jsonObject.optJSONArray("pages").length() > 0) {
                for (int j = 0; j < jsonObject.optJSONArray("pages").length(); j++) {
                    allPages.put(jsonObject.optJSONArray("pages").getJSONObject(j));
                }
            }
            if (jsonObject.optJSONArray("catalogs").length() > 0) {

                return getAllPages(jsonObject.optJSONArray("catalogs"), allPages);
            }
        }
        return allPages;
    }
}
